<?php

class UsuariosController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	
	
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),			
		);
	}
	
	
	
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','registrarse','captcha'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','modificarPerfil','buscar','cumpleano'),
				'users'=>array('@'),
			),
			array( 'allow',
            'actions'=>array('admin','create','delete','update','administrar'),
            'expression'=>'$user->isAdmin()'
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Usuarios;
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Usuarios']))
		{
			$model->attributes=$_POST['Usuarios'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->idusuario));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
	
	
	public function actionModificarPerfil()
	{	
	//	if(Yii::app()->session['idusuario']==$_GET['id']){
			//$model=new Usuarios;
			$model=Usuarios::model()->findByPk(Yii::app()->session['idusuario']);
			//$model=Usuarios::model()->findByPk($_GET['id']);
			// Uncomment the following line if AJAX validation is needed
			// $this->performAjaxValidation($model);
			if(isset($_POST['Usuarios']))
			{
				$model->attributes=$_POST['Usuarios'];
				if($model->save()){
					Yii::app()->session['nombre'] = $model->nombre;
					Yii::app()->session['apellido'] = $model->apellido;
					Yii::app()->session['mail'] = $model->mail;
					Yii::app()->session['sexo'] = $model->sexo;
					Yii::app()->session['fechaNacimiento'] = $model->fechaNacimiento;
//----------------------------------------------------------------------------------------
// Alertar de cambio de informacion de perfil (caso de uso informar actualizacion perfil)	
//----------------------------------------------------------------------------------------
					$this->redirect(array('comentarios/vercomentariosmuro'));
					}
			}
			$this->render('modificarPerfil',array('model'=>$model,));
		//}else{
		//$this->redirect(array('site/index'));
		//}//
	}
	
	
	
	public function actionBuscar()	
	{
		$count=Yii::app()->db->createCommand('select count(*) from usuarios where idusuario not in (select idamigo from amigos where idusuario='.Yii::app()->session['idusuario'].') AND idusuario!='.Yii::app()->session['idusuario'])->queryScalar();
		$sql='select * from usuarios where idusuario not in (select idamigo from amigos where idusuario='.Yii::app()->session['idusuario'].') AND idusuario!='.Yii::app()->session['idusuario'];
		$dataProvider=new CSqlDataProvider($sql, array(
		'keyField'=>'idusuario',
		'totalItemCount'=>$count,
		'sort'=>array(
			'attributes'=>array(
				'idusuario', 'nombre', 'apellido',
			),
		),
		'pagination'=>array(
			'pageSize'=>25,
		),
	));
		$this->render('buscar',array('model'=>$dataProvider,));
	}
	
	public function actionCumpleano(){
		// SELECT * FROM amigos  JOIN usuarios ON amigos.idamigo = usuarios.idusuario WHERE fechaNacimiento = CURDATE( ) AND amigos.idusuario =3
	
		$count=Yii::app()->db->createCommand('SELECT count(*) FROM amigos  JOIN usuarios ON amigos.idamigo = usuarios.idusuario WHERE
		 amigos.idusuario='.Yii::app()->session['idusuario'].' AND DATE_FORMAT(usuarios.fechaNacimiento,\'%m-%d\') = DATE_FORMAT(NOW(),\'%m-%d\')  ')->queryScalar();
		
			
		//$count=Yii::app()->db->createCommand('SELECT count(*) FROM amigos  JOIN usuarios ON amigos.idamigo = usuarios.idusuario WHERE fechaNacimiento = CURDATE( ) AND amigos.idusuario ='.Yii::app()->session['idusuario'])->queryScalar();
		$sql='SELECT * FROM amigos  JOIN usuarios ON amigos.idamigo = usuarios.idusuario WHERE
		 amigos.idusuario='.Yii::app()->session['idusuario'].' AND DATE_FORMAT(usuarios.fechaNacimiento,\'%m-%d\') = DATE_FORMAT(NOW(),\'%m-%d\')' ;
		$dataProvider=new CSqlDataProvider($sql, array(
		'keyField'=>'idusuario',
		'totalItemCount'=>$count,
		'sort'=>array(
			'attributes'=>array(
				'idusuario', 'nombre', 'apellido','fechaNacimiento',
			),
		),
		'pagination'=>array(
			'pageSize'=>25,
		),
	));
		$this->render('cumpleano',array('model'=>$dataProvider,));
	
	}
	
	
	public function actionRegistrarse()
	{
		$model=new Usuarios;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Usuarios']))
		{
			$model->attributes=$_POST['Usuarios'];
			$existe=Usuarios::model()->find('mail=?',array($model->mail));
			if($existe==null){			
				if($model->save()){
					$this->redirect(array('comentarios/vercomentariosmuro','idusuario'=>$model->idusuario));
				}
			}else{			
				Yii::app()->user->setFlash('error', '<strong>ERROR!</strong> El usuario ya esta registrado.');
			}
		}

		$this->render('registrarse',array(
			'model'=>$model,
		));
	}
	

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Usuarios']))
		{
			$model->attributes=$_POST['Usuarios'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->idusuario));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Usuarios');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Usuarios('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Usuarios']))
			$model->attributes=$_GET['Usuarios'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	
	public function actionAdministrar()
	{
		$model=new Usuarios('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Usuarios']))
			$model->attributes=$_GET['Usuarios'];

		$this->render('administrar',array(
			'model'=>$model,
		));
	}
	
	
	

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Usuarios the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Usuarios::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Usuarios $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='usuarios-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
